from flask import current_app, jsonify
from flask import g
from flask import render_template,session
from flask import request

from info import constants
from info.models import User, News, Category
from info.utits.common import user_login_data
from info.utits.response_code import RET
from . import index_bp
from info import models


@index_bp.route('/')
@user_login_data
def index():
    """新闻首页"""
    user = g.user
    try:
        news_rank_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询点击排行数据异常")

    news_rank_dict_list = []
    for news_obj in news_rank_list if news_rank_list else []:
        news_dict = news_obj.to_dict()
        news_rank_dict_list.append(news_dict)

    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询分类数据异常")
    category_dict_list = []
    for category in categories if categories else []:
        category_dict_list.append(category.to_dict())
    data = {
        "user_info": user.to_dict() if user else None,
        "news_rank_list": news_rank_dict_list,
        "categories":category_dict_list
    }
    return render_template("news/index.html",data=data)


@index_bp.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")


@index_bp.route('/news_list')
def get_news_list():
    """获取新闻列表数据"""
    param_dict = request.args
    cid = param_dict.get("cid","1")  # 分类号
    page = param_dict.get("page","1") # 页号
    per_page = param_dict.get("per_page","10")  # 每一页显示的新闻条数

    if not cid:
        return jsonify(error=RET.PARAMERR,errmsg="参数不足")
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.PARAMERR,errmsg="参数格式错误")

    filters = [News.status==0]
    if cid != 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)

        items = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询新闻列表数据异常")

    news_dict_list = []   # 对象列表转换成字典列表
    for news in items if items else []:
        news_dict_list.append(news.to_dict())

    data = {
        "news_list": news_dict_list,
        "current_page":current_page,
        "total_page":total_page
    }
    return jsonify(error=RET.OK,errmsg="查询新闻列表数据成功",data=data)